//
//  MKCDeviceAuthorizationManager.m
//  ELearningClient
//
//  Created by zh on 2019/5/13.
//

#import "EMDeviceAuthorizationManager.h"
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>
#import "UIViewController+ShowAlertController.h"

@interface EMDeviceAuthorizationManager ()

@property (strong, nonatomic) AVCaptureSession *session;//媒体管理会话
@property (strong, nonatomic) AVCaptureDeviceInput *captureInput;//输入数据对象
@property (strong, nonatomic) AVCaptureStillImageOutput *imageOutput;//输出数据对象
@property (strong, nonatomic) AVCaptureVideoPreviewLayer *captureLayer;//视频预览图层

@end


@implementation EMDeviceAuthorizationManager

+ (instancetype)shareManager{
    static EMDeviceAuthorizationManager* _sharedInstanced = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (_sharedInstanced == nil) {
            _sharedInstanced = [[EMDeviceAuthorizationManager alloc]init];
        }
    });
    return _sharedInstanced;
}

+ (void)popupPhotoLibraryInVC:(UIViewController<UINavigationControllerDelegate, UIImagePickerControllerDelegate>*)vc
{
    if (!vc) {
        return;
    }

    void(^popImagePickerVC)(void) = ^() {
        dispatch_async(dispatch_get_main_queue(), ^{
            UIImagePickerController *imagePC = [UIImagePickerController new];
            imagePC.delegate = vc;
            //imagePC.allowsEditing = YES;
            imagePC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            imagePC.modalPresentationStyle = UIModalPresentationFullScreen;
            [vc presentViewController:imagePC animated:YES completion:nil];
        });

    };

    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        //权限判断
        PHAuthorizationStatus author = [PHPhotoLibrary authorizationStatus];
        if (author == PHAuthorizationStatusNotDetermined) {
            //还没决定
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                //发起权限请求
                if (status == PHAuthorizationStatusAuthorized) {
                    //用户授权
                    popImagePickerVC();
                } else {
                    //用户拒绝
                    //暂时什么都不做
                }
            }];
        } else if (author ==PHAuthorizationStatusRestricted || author ==PHAuthorizationStatusDenied) {
            //无权限 引导去开启
            [self showAlertMessage:vc];
        } else {
            //先弹出vc
            popImagePickerVC();
        }
    }
    else
    {
        [vc showAlertMessage:nil withTitle:NSLocalizedString(@"相册不可用", nil)];
    }
}

+ (void)popupCameraInVC:(UIViewController *)vc delegate:(id<UINavigationControllerDelegate, UIImagePickerControllerDelegate>)delegate
{
    if (!vc) {
        return;
    }

    void(^popCameraVC)(void) = ^() {
        //弹出vc
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = delegate;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        imagePicker.allowsEditing = YES;
        imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
        [vc presentViewController:imagePicker animated:YES completion:nil];
    };

    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        //权限判断
        AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authorizationStatus == AVAuthorizationStatusNotDetermined) {
            //还没决定
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    //用户同意
                    popCameraVC();
                } else {
                    //如果第一次用户拒绝了，回调并不在主线程。（注意，此时的status仍然是用户并未决定）
                    //暂时什么都不做
                }
            }];
        }
        else if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied) {
            //No auth
            [self showAlertMessage:vc];

        } else {
            //权限允许
            popCameraVC();
        }
    } else {
         [vc showAlertMessage:nil withTitle:NSLocalizedString(@"摄像头不可用", nil)];
    }
}

+ (void)showAlertMessage:(UIViewController *)vc{

    UIAlertAction *cancelAct = [UIAlertAction actionWithTitle:NSLocalizedString(@"取消", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

    }];

    UIAlertAction *setAct = [UIAlertAction actionWithTitle:NSLocalizedString(@"前往设置", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL:url];
    }];

    [vc showAlertMessage:NSLocalizedString(@"请在iPhone的'设置->隐私->相机'选项中，允许PinMoney访问你的相机", nil) withTitle:NSLocalizedString(@"提示", nil) withActions:@[cancelAct,setAct]];

}

- (void)initCapture:(UIView *)superView{
    //1. 创建媒体管理会话
    AVCaptureSession *session = [[AVCaptureSession alloc] init];
    self.session = session;
    //判断分辨率是否支持1280*720，支持就设置为1280*720
    if( [session canSetSessionPreset:AVCaptureSessionPreset1280x720] ) {
        session.sessionPreset = AVCaptureSessionPreset1280x720;
    }
    //2. 获取后置摄像头设备对象
    AVCaptureDevice *device = nil;
    NSArray *cameras = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *camera in cameras) {
        if (camera.position == AVCaptureDevicePositionFront) {//取得前置摄像头
            device = camera;
        }
    }
    if(!device) {
        NSLog(@"取得前置摄像头错误");
        return;
    }
    //3. 创建输入数据对象
    NSError *error = nil;
    AVCaptureDeviceInput *captureInput = [[AVCaptureDeviceInput alloc] initWithDevice:device
                                                                                error:&error];
    if (error) {
        NSLog(@"创建输入数据对象错误");
        return;
    }
    self.captureInput = captureInput;
    //4. 创建输出数据对象
    AVCaptureStillImageOutput *imageOutput = [[AVCaptureStillImageOutput alloc] init];
    NSDictionary *setting = @{ AVVideoCodecKey:AVVideoCodecJPEG };
    [imageOutput setOutputSettings:setting];
    self.imageOutput = imageOutput;
    //5. 添加输入数据对象和输出对象到会话中
    if ([session canAddInput:captureInput]) {
        [session addInput:captureInput];
    }
    if ([session canAddOutput:imageOutput]) {
        [session addOutput:imageOutput];
    }
    //6. 创建视频预览图层
    AVCaptureVideoPreviewLayer *videoLayer =
    [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
    videoLayer.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    videoLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    self.captureLayer = videoLayer;
}


- (void)starCapture:(UIView *)superView{

    if (!self.session) {
        [self initCapture:superView];
    }

    if (!self.captureLayer.superlayer) {
        [superView.layer insertSublayer:self.captureLayer atIndex:0];
    }
    if (self.session.isRunning == NO) {
        [self.session startRunning];
    }
}

- (void)stopCapture{

    if (self.session.isRunning) {
        [self.captureLayer removeFromSuperlayer];
        [self.session stopRunning];
    }

}









@end
